<?php


namespace console\controllers;

use Yii;
use yii\console\Controller;
use common\models\patient\Callback;

class ReportCallbackController extends Controller
{
    /**
     * 回访曲线统计定时任务
     *
     * @return int
     * @throws \yii\db\Exception
     * @author chenyuebin
     */
    public function actionFollowTiming()
    {
        return Yii::$app->services->patientCallback->reportCallback();
    }

    public function actionCallbackNum()
    {
        return Yii::$app->services->patientCallback->callbacknum();
    }

    /**
     * 0 0 * * * php yii report-callback/statistics 0 2020-01-01
     *
     * 回访报表【统计昨日回访数据】
     */
    public function actionStatistics($startDate = null, $endDate = null)
    {
        try {
            if ($startDate || $endDate) {// 传参
                if (empty($startDate)) {
                    $minCallbackTime = Callback::find()
                        ->where([
                            'and',
                            ['=', 'status', Callback::STATUS_ENABLE],
                            ['>', 'current_callback_time', 0],
                        ])
                        ->min('current_callback_time');
                    $startDate = date('Y-m-d', $minCallbackTime);
                }

                if (empty($endDate)) {
                    $maxCallbackTime = Callback::find()
                        ->where(['status' => Callback::STATUS_ENABLE])
                        ->max('current_callback_time');
                    $endDate = date('Y-m-d', $maxCallbackTime);
                }

                $startDateTime = strtotime($startDate);
                $endDateTime = strtotime($endDate);
                $diff = $endDateTime - $startDateTime;
                if ($diff < 0) {
                    throw new \Exception("开始时间不能大于结束时间[{$startDate}~~{$endDate}]");
                }
            } else {// 默认昨天
                $diff = 0;

                // 截止日期
                $startDate = date("Y-m-d", strtotime("-1 day"));
                $startDateTime = strtotime($startDate);
            }
            $times = intval($diff/86400);

            for ($i = 0; $i <= $times; $i++) {
                $expDate = date('Y-m-d', $startDateTime + $i*86400);

                $param = [
                    'date' => $expDate
                ];
                $res = Yii::$app->services->statisticsCallbackReport->statistics($param);
                echo $expDate.'--'.$res.PHP_EOL;
            }
        } catch (\Exception $e) {
            echo $e->getMessage().PHP_EOL;
        }
    }
}
